package cn.stylefeng.guns.modular.robot.cmd.impl;

import cn.stylefeng.guns.modular.robot.cmd.abs.AbstractCmd;
import cn.stylefeng.guns.modular.robot.entity.Group;
import cn.stylefeng.guns.modular.robot.entity.GroupManager;
import cn.stylefeng.guns.modular.robot.service.GroupManagerService;
import cn.stylefeng.guns.modular.robot.service.GroupService;
import cn.stylefeng.guns.modular.robot.utils.RobotUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.api.objects.User;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;

@Slf4j
@Service
@Transactional
public class MgrCmdBiz {

    @Resource
    private List<AbstractCmd> cmds;
    @Resource
    private GroupManagerService groupManagerService;
    @Resource
    private GroupService groupService;

    private List<String> cmdIgnore = Arrays.asList("获取群ID");

    public void handle(Update update, TelegramLongPollingBot bot) {
        if (!verifyAuthority(update)) {
            return;
        }
        for (AbstractCmd cmd : cmds) {
            cmd.execCmd(update, bot);
        }
    }

    private boolean verifyAuthority(Update update) {
        String text = update.getMessage().getText();
        Long chatId = update.getMessage().getChatId();
        //验证用户是否有执行命令的权限
        User from = update.getMessage().getFrom();
        List<GroupManager> groupManagers = groupManagerService.lambdaQuery()
                .eq(GroupManager::getGroupId, chatId)
                .eq(GroupManager::getUserName, from.getUserName())
                .list();
        List<Group> groups = groupService.lambdaQuery()
                .eq(Group::getTgGroupId, chatId)
                .eq(Group::getUserName, from.getUserName())
                .list();
        boolean isMgr = !CollectionUtils.isEmpty(groupManagers) || !CollectionUtils.isEmpty(groups);
        //非命令，媒体文件,不校验权限
        if (StringUtils.isBlank(text)) {
            return isMgr;
        }
        //忽略权限的指令
        for (String cmd : cmdIgnore) {
            if (text.toUpperCase(Locale.ROOT).startsWith(cmd)) {
                return true;
            }
        }
        return isMgr;
    }
}
